
importClass("java.io.File");
importClass("java.util.Scanner");
importClass("java.io.FileOutputStream");
importClass("java.io.PrintWriter");

function FileClient() {
    /**
     * 删除文件或目录.
     * @param fileName 文件名，目录名.
     * @returns {*}
     */
    this.delete = function (fileName) {
        if ("/" === fileName || null === fileName|| "" === fileName) {
            console.info("file not support. fileName = " + fileName);
            return false;
        }
        var file = new File(fileName);
        if (!file.exists()) {
            console.info("file not exists. fileName = " + fileName);
            return false;
        }
        if (file.isDirectory()) {
            var files = file.listFiles();
            if (null != files) {
                var files_length = files.length;
                for(var files_index = 0; files_index < files_length; files_index ++) {
                    this.delete(files[files_index].getAbsolutePath())
                }
            }
        }
        var status = file.delete();
        if (status) {
            console.info("delete success. fileName = " + fileName);
        } else {
            console.info("delete failed. fileName = " + fileName);
        }
        return status;
    };

    /**
     * 数据处理.
     * @param srcFile 原文件.
     * @param targetFile 目标文件.
     * @param callbackFunction 回调处理.
     * @param endFunction 回调处理.
     */
    this.processFile = function(srcFile, targetFile, callbackFunction, endFunction) {
        if (null == srcFile || !srcFile) {
            console.info("srcFile is empty.");
            return;
        }
        // 如果第二参数是方法，自动转为callbackFunction
        if ('function' === typeof(targetFile)) {
            callbackFunction = targetFile;
            targetFile = null;
        }
        if (!callbackFunction) {
            throw "callbackFunction not exists.";
        }
        var fileEveryWhere = util.getFileEveryWhere(srcFile);
        if (null == fileEveryWhere) {
            throw "not found file = " + srcFile;
        }
        var scanner = null;
        var out = null;

        try {
            scanner = new Scanner(fileEveryWhere.openStream());
            if (null != targetFile && targetFile) {
                out = new PrintWriter(new FileOutputStream(targetFile));
            }
            var line = null;
            while (scanner.hasNextLine()) {
                line = scanner.nextLine();
                var callbackStatus = callbackFunction(line, out);
                if (null != callbackStatus && !callbackStatus) {
                    break;
                }
            }
            if (endFunction) {
                endFunction(out,srcFile);
            }
        } finally {
            util.closeQuietly(scanner);
            if (null != out) {
                out.flush();
            }
            util.closeQuietly(out);
        }
    }
}